<template>
  <el-form ref="baseRuleForm" :rules="rules" :model="baseInfo" class="lineHeight32" label-width="110px" label-position="right">
    <el-row class="response-el-row">
      <el-col :span="12" class="responsive-col-lg-8">
        <el-form-item label="申请人" prop="proposerId">
          <el-select
            v-loadmore="userLoadMore"
            :value="baseInfo.proposerId"
            :filter-method="filterProposerData"
            :disabled="invoiceStatus === 1"
            filterable
            class="filterableSelect remoteRequest1"
            popper-class="global-select-down"
            default-first-option
            placeholder="请选择申请人"
            @change="selectChange($event, 'proposerId')"
          >
            <el-option
              v-for="(select) in proposerList.items"
              :key="select.id"
              :label="select.userName"
              :value="select.id" />
            <div v-if="proposerListLoading" class="loading-container"><i class="el-icon-loading"/></div>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12" class="responsive-col-lg-8">
        <el-form-item label="申请部门" prop="deptId">
          <el-select v-model="baseInfo.deptId" :disabled="invoiceStatus === 1" name="deptId" popper-class="global-select-down" @change="selectChange($event, 'deptId')">
            <el-option
              v-for="item in deptList"
              :key="item.id"
              :label="item.value"
              :value="item.id" />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12" class="responsive-col-lg-8">
        <el-form-item label="发票抬头" prop="title">
          <!-- <el-input
              :value="baseInfo.title"
              placeholder="请输入我方抬头"
              name="title"
              type="text"
              maxlength="50"
              @input="textInputChange($event, 'title')"
            /> -->
          <el-autocomplete
            :value="baseInfo.title"
            :fetch-suggestions="queryTitleSearchAsync"
            :maxlength="20"
            :disabled="invoiceStatus === 1"
            placeholder="发票抬头"
            name="title"
            @input="autocompleteChange($event, 'title')"
            @change="textInputChange($event, 'title')"
          />
        </el-form-item>
      </el-col>
      <el-col :span="12" class="responsive-col-lg-8">
        <el-form-item label="发票类型" prop="invoiceTypeId">
          <el-select v-model="baseInfo.invoiceTypeId" :disabled="invoiceStatus === 1" name="invoiceTypeId" popper-class="global-select-down" @change="selectChange($event, 'invoiceTypeId')">
            <el-option
              v-for="item in invoiceTypes"
              :key="item.id"
              :label="item.name"
              :value="item.id" />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12" class="responsive-col-lg-8">
        <el-form-item v-if="clientShow" label="纳税人名称" prop="customerId">
          <el-select
            v-loadmore="clientLoadMore"
            :value="baseInfo.customerId"
            :filter-method="filterClientData"
            :disabled="invoiceStatus === 1"
            popper-class="global-select-down"
            filterable
            class="filterableSelect remoteRequest2"
            default-first-option
            placeholder="请选择纳税人"
            @change="customerChange($event)"
          >
            <el-option
              v-for="(select) in customerList.items"
              :key="select.id"
              :label="select.clientName || ' '"
              :value="select.id" />
            <div v-if="clientListLoading" class="loading-container"><i class="el-icon-loading"/></div>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12" class="responsive-col-lg-8">
        <el-form-item label="纳税人识别号" prop="taxpayerNum">
          <el-input
            :value="baseInfo.taxpayerNum"
            :disabled="true"
            placeholder=""
            name="taxpayerNum"
            type="text"
          />
        </el-form-item>
      </el-col>
      <el-col :span="12" class="responsive-col-lg-8">
        <el-form-item label="开票日期" prop="date">
          <el-date-picker
            v-model="invoiceDate"
            :editable="false"
            :disabled="invoiceStatus === 1"
            type="date"
            placeholder="请输入开票日期"
            value-format="timestamp"
            format="yyyy/MM/dd"
            @change="publishTimeChange($event, 'date')"
          />
        </el-form-item>
      </el-col>
      <el-col :span="12" class="responsive-col-lg-8">
        <el-form-item :style="{ 'width': showMobilePage ? 'unset' : '500px' }" label="关联订单" prop="relatedOrder">
          <!-- <RelatedOrder :ids="orderIds" :options="options" @postMessage="getRelatedOrder"/> -->
          <relevance-order :orders="orderIds" @postMessage="getRelatedOrder" />
        </el-form-item>
      </el-col>
      <el-col :span="12" class="responsive-col-lg-8">
        <el-form-item label="开户行" prop="openBank">
          <el-input
            :value="baseInfo.openBank"
            :disabled="true"
            placeholder=""
            name="openBank"
            type="text"
          />
        </el-form-item>
      </el-col>
      <el-col :span="12" class="responsive-col-lg-8">
        <el-form-item label="开票地址" prop="invoiceAddress">
          <el-input
            :value="baseInfo.invoiceAddress"
            :disabled="true"
            placeholder=""
            name="invoiceAddress"
            type="text"
          />
        </el-form-item>
      </el-col>
      <el-col :span="12" class="responsive-col-lg-8">
        <el-form-item label="开户账号" prop="accountNum">
          <el-input
            :value="baseInfo.accountNum"
            :disabled="true"
            placeholder=""
            name="accountNum"
            type="text"
          />
        </el-form-item>
      </el-col>
      <el-col :span="12" class="responsive-col-lg-8">
        <el-form-item label="注册电话" prop="phone">
          <el-input
            :value="baseInfo.phone"
            :disabled="true"
            placeholder=""
            name="phone"
            type="text"
          />
        </el-form-item>
      </el-col>
      <el-col :span="12" class="responsive-col-lg-8">
        <el-form-item label="含税金额" prop="amount">
          <el-input
            :value="baseInfo.amount"
            :disabled="invoiceStatus === 1"
            placeholder="请输入含税金额"
            name="amount"
            type="text"
            maxlength="15"
            @input="numInputChange($event, 'amount')"
          />
        </el-form-item>
      </el-col>
      <el-col :span="12" class="responsive-col-lg-8">
        <el-form-item label="备注" prop="remark">
          <el-input
            :value="baseInfo.remark"
            :disabled="invoiceStatus === 1"
            name="remark"
            type="text"
            maxlength="500"
            @input="textInputChange($event, 'remark')"
          />
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
</template>
<script>
import { getList } from '@/api/customer';
import { getList as getUserList } from '@/api/user';
import { deptList } from '@/api/select';
import { getInvoiceTypes, invoiceTitleSearch } from '@/api/invoice';
import RelatedOrder from '@/components/RelatedOrder';
import RelevanceOrder from '@/components/relevanceOrder';
export default {
  name: 'BaseInfoEdit',
  components: { RelatedOrder, RelevanceOrder },
  props: {
    baseInfo: {
      type: Object,
      default: () => {
        return {
          proposerId: '',
          deptId: '',
          title: '',
          invoiceTypeId: '',
          customerId: '',
          clientName: '',
          taxpayerNum: '',
          date: '',
          relatedOrder: [],
          openBank: '',
          accountNum: '',
          phone: '',
          amount: '',
          remark: '',
          invoiceAddress: ''
        };
      }
    },
    invoiceStatus: {
      type: Number,
      default: 0
    },
    defaultProposerList: {
      type: Array,
      default: () => []
    },
    defaultCustomerList: {
      type: Array,
      default: () => []
    },
    orderIds: {
      type: Array,
      default: () => []
    },
    isUpdate: {
      type: Boolean,
      default: false
    },
    updateCustomers: {
      type: Object,
      default: () => null
    },
    relatedOrder: {
      type: Array,
      default: () => []
    },
    isInit: {
      type: Boolean,
      default: true
    },
    showMobilePage: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      proposerName: '',
      clientName: '',
      deptList: [],
      title: '',
      invoiceTypes: [],
      ids: [],
      options: [],
      proposerListLoading: false,
      clientListLoading: false,
      invoiceDate: '',
      clientShow: true,
      isOrderInit: false,
      proposerList: {
        items: [],
        total: 0,
        page: 1,
        perPage: 20,
        isInit: true
      },
      customerList: {
        items: [],
        total: 0,
        page: 1,
        perPage: 20,
        isInit: true
      },
      rules: {
        'proposerId': [{ required: true, message: '请选择申请人', trigger: 'change' }],
        'date': [{ required: true, message: '请选择开票日期', trigger: 'change' }],
        'amount': [{ required: true, message: '请输入开票金额', trigger: 'change' }]
      }
    };
  },
  computed: {
    isOrderEdit() {
      return this.isEdit;
    }
  },
  watch: {
    'baseInfo.date': {
      handler(newValue, oldValue) {
        this.invoiceDate = newValue;
      }
    },
    'baseInfo.relatedOrder': {
      handler(newValue, oldValue) {
        if (this.options.length === 0 && newValue.length > 0 && !this.isInit && !this.isOrderInit) {
          this.options = newValue;
        }
        this.isOrderInit = true;
      }
    },
    defaultProposerList(newV) {
      this.proposerList.items = newV;
    },
    updateCustomers(newValue, oldValue) {
      if (newValue) {
        if (newValue.id === this.customerList.items[0].id) {
          // this.customerList.items.splice(0, 1);
          this.$set(this.customerList.items, 0, { clientName: newValue.clientName, id: newValue.id });
          // this.clientShow = true;
          // this.customerList.items[0].clientName = newValue.clientName;
          // this.customerList.items = JSON.parse(JSON.stringify(this.customerList.items));
          // console.log(this.customerList.items);
        }
      }
    }
  },
  created() {
    this.getProposerList();
    this.getDeptList();
    this.getClientList();
    this.getInvoiceTypes();
    // console.log('create', this.defaultProposerList);
    // this.proposerList.items = this.defaultProposerList;
    // this.customerList.items = this.defaultCustomerList;
    // this.value = this.baseInfo.date;
    window.removeReadOnly();
  },
  mounted() {
    window.remoteRequest('.remoteRequest1', this.filterProposerData);
    window.remoteRequest('.remoteRequest2', this.filterClientData);
  },
  methods: {
    // 提供给父组件来验证完整性
    validateForm(validate = true, index = 0) {
      return new Promise((resolve, reject) => {
        if (validate) {
          this.$refs.baseRuleForm.validate(valid => {
            if (valid) {
              resolve(valid);
            } else {
              reject(index);
            }
          });
        } else {
          resolve(true);
        }
      });
    },
    queryTitleSearchAsync(queryString, cb) {
      invoiceTitleSearch(queryString).then(res => {
        if (res.code === 200) {
          const items = res.data;
          cb(items);
        }
      });
    },
    // 从列表中去除 已经有的数据
    handeldefaultList(list, defaultList) {
      let res = [];
      if (list && list.length > 0) {
        const ids = defaultList.map(i => i.id);
        res = list.filter(i => {
          return !ids.includes(i.id);
        });
      }
      return res;
    },
    getDeptList() {
      deptList().then(res => {
        if (res.code === 200) {
          this.deptList = res.data;
        }
      });
    },
    getInvoiceTypes() {
      getInvoiceTypes().then(res => {
        if (res.code === 200) {
          this.invoiceTypes = res.data;
        }
      });
    },
    getProposerList(page = 1, userName = '') {
      this.proposerListLoading = true;
      // if (this.proposerList.total >= this.proposerList.items.length) {
      //   this.proposerListLoading = false;
      //   return;
      // }
      getUserList(page, 15, { userName, type: 1 }).then(({ data }) => {
        this.proposerListLoading = false;
        if (page > 1 && this.proposerList.items) {
          data.items = this.handeldefaultList(data.items, this.defaultProposerList);
          const concatList = this.proposerList.items.concat(data.items);
          data.items = concatList;
          this.proposerList = data;
        } else {
          data.items = this.handeldefaultList(data.items, this.defaultProposerList);
          this.proposerList.items = this.defaultProposerList;
          if (!userName) {
            const concatList = this.proposerList.items.concat(data.items);
            data.items = concatList;
          }
          this.proposerList = data;
        }
      }, result => {
        this.proposerListLoading = false;
      }).catch(e => {
        console.error(e);
      });
    },
    getClientList(page = 1, clientName = '') {
      this.clientListLoading = true;
      // if (this.customerList.total >= this.customerList.items.length) {
      //   this.proposerListLoading = false;
      //   return;
      // }
      getList({ page, perPage: 15, clientName }).then(({ data, total }) => {
        this.clientListLoading = false;
        if (page > 1 && this.customerList.items) {
          data.items = this.handeldefaultList(data.items, this.defaultCustomerList);
          const concatList = this.customerList.items.concat(data.items);
          data.items = concatList;
          this.customerList = data;
        } else {
          data.items = this.handeldefaultList(data.items, this.defaultCustomerList);
          this.customerList.items = this.defaultCustomerList;
          if (!clientName) {
            const concatList = this.customerList.items.concat(data.items);
            data.items = concatList;
          }
          this.customerList = data;
        }
      }, result => {
        this.clientListLoading = false;
      }).catch(e => {
        console.error(e);
      });
    },
    // 滚动加载更多申请人
    userLoadMore() {
      const proposerList = this.proposerList;
      const currentPage = proposerList.page;
      if (proposerList.items) {
        // const isMax = userList.items.length >= userList.total;
        if (this.proposerList.total <= this.proposerList.items.length) {
          this.proposerListLoading = false;
          return;
        }
        if (proposerList.items.length < 300 && !this.proposerListLoading) {
          this.getProposerList(currentPage + 1, this.proposerName);
        }
      }
    },
    // 滚动加载更多客户
    clientLoadMore() {
      const customerList = this.customerList;
      const currentPage = customerList.page;
      if (customerList.items) {
        // const isMax = userList.items.length >= userList.total;
        if (this.customerList.total <= this.customerList.items.length) {
          this.proposerListLoading = false;
          return;
        }
        if (customerList.items.length < 300 && !this.clientListLoading) {
          this.getClientList(currentPage + 1, this.clientName);
        }
      }
    },
    selectChange(type, prop) {
      const baseInfo = { ...this.baseInfo };
      baseInfo[prop] = type;
      this.$emit('update:baseInfo', baseInfo);
    },
    textInputChange(text, prop) {
      const baseInfo = { ...this.baseInfo };
      baseInfo[prop] = text;
      this.$emit('update:baseInfo', baseInfo);
    },
    autocompleteChange(data, prop) {
      const baseInfo = { ...this.baseInfo };
      baseInfo[prop] = data;
      this.$emit('update:baseInfo', baseInfo);
    },
    publishTimeChange(date, prop) {
      const baseInfo = { ...this.baseInfo };
      baseInfo[prop] = date;
      this.$emit('update:baseInfo', baseInfo);
    },
    numInputChange(text, prop) {
      let str = text.replace(/[^\d.]/g, ''); // 只允许数字
      str = str.replace(/\.{2,}/g, '.'); // 连续两个小数点 replace为.
      str = str.replace(/^\./g, '0.'); // 已点为开头 replace为 0.
      str = str.replace(/^(\d*)\.(\d*)\./g, '$1.$2');// 不连续点点 删掉
      str = str.replace(/^0[^\.]+/g, '0'); // 连续多个0 replace为1个0
      str = str.replace(/^(\d+)\.(\d\d).*$/, '$1.$2'); // 只允许保留小数点后3位
      const baseInfo = { ...this.baseInfo };
      baseInfo[prop] = str;
      this.$emit('update:baseInfo', baseInfo);
    },
    getRelatedOrder(params) {
      const baseInfo = { ...this.baseInfo };
      baseInfo['relatedOrder'] = params.relatedOrderOptions;
      this.$emit('update:baseInfo', baseInfo);
    },
    // 用于手动触发表单验证
    triggerFormValidate() {
      this.$refs.baseRuleForm.validate();
    },
    // 纳税人名称改变的操作
    customerChange(data) {
      const customerList = this.customerList.items;
      let target;
      for (let i = 0; i < customerList.length; i++) {
        if (customerList[i].id === data) {
          target = customerList[i];
          break;
        }
      }
      const baseInfo = { ...this.baseInfo };
      baseInfo['customerId'] = data;
      if (target) {
        baseInfo['clientName'] = target['clientName'];
        baseInfo['taxpayerNum'] = target['taxpayerNum'];
        baseInfo['openBank'] = target['openBank'];
        baseInfo['invoiceAddress'] = target['invoiceAddress'];
        baseInfo['phone'] = target['phone'];
        baseInfo['accountNum'] = target['accountNum'];
        this.$emit('update:baseInfo', baseInfo);
      }
      this.$emit('update:baseInfo', baseInfo);
    },
    // 过滤纳税人名称
    filterClientData(val) {
      this.clientName = val;
      this.getClientList(1, val);
    },
    // 过滤申请人
    filterProposerData(val) {
      this.proposerName = val;
      this.getProposerList(1, val);
    },
    proposerInput(value) {
      // console.log(value);
    }
  }
};
</script>
<style lang="scss" scoped>
.loading-container {
  width: 100%;
  text-align: center;
  i {
    color: #999;
  }
}
</style>
<style lang="scss">
.base-info-edit-box {
  .el-tag.el-tag--info {
    color: #406EFF;
    background-color: #ecf1ff;
  }
}
</style>
